
var common = require('../common.js');
var casecommon = require('../casecommon.js');
var urlx = require('url');
var http = require('http');

var index = 0;
var url = '';
var recvdata = '';
var statuscode = 0;
var clients = {};

function queryUrl(urla) {
    var host = urlx.parse(urla);
    var path = host['pathname'];
    if(host['search']!=null) path += host['search'];
    var port = 80;
    host = host['host'];
    var loc = host.indexOf(':')
    if(loc>=0) {
        port = host.substring(loc+1);
        host = host.substring(0, loc); 
    }

    client = clients[host+':'+port];
    if(client==null) {
    	client = http.createClient(port, host);
        clients[host+':'+port] = client;
    }

    return client.request('GET', path, { 'Content-Type': 'application/x-www-form-urlencoded' });
}

function do_login() {
    if((index%2)==0) {
        url = 'http://192.168.0.135/mocool/api_register.php?username=u'+casecommon.genUsername(index/2)+'&password=abcdef';
    } else {
        url = 'http://192.168.0.135/mocool/api_register.php?device_id=d'+casecommon.genUsername((index-1)/2);
    }
    index++;

    if(index>200000) {
        process.exit(0);
    }

    var req = queryUrl(url);
    req.on('response' , function(res) {
        statuscode = res.statusCode;
        recvdata = '';
        res.on('data', function(data) {
            recvdata += data;
        });
        res.on('end', function() {
            common.rlog('url   =' + url);
            common.rlog('status=' + statuscode);
            common.rlog('return=' + recvdata);
            do_login();
        });
        res.on('error', function(err) {
            common.rlog('url   =' + url);
            common.rlog('err   =' + err);
            do_login();
        });
    });
    req.end();
}

exports.initNodes = function (tree) {
};

exports.initTree = function (tree) {
};

exports.initCase = function () {
    var arg_proc = {
        'start' : function (arg) { index = arg; }
    };
};

exports.run = function () {
    do_login();
};

exports.finiCase = function () {
    setInterval(function() {
    }, 1000);
};
